//
//  LCAppDelegate.m
//
//
//  Created by admin on 2017/1/6.
//  Copyright © 2017年 admin. All rights reserved.
//

#import "LCAppDelegate.h"
#import <ShareSDK/ShareSDK.h>
#import <ShareSDKConnector/ShareSDKConnector.h>
#import <TencentOpenAPI/TencentOAuth.h>
#import <TencentOpenAPI/QQApiInterface.h>
#import "WeiboSDK.h"
#import "WXApi.h"
#import "SVProgressHUD.h"
#import "NetworkTool.h"
#import "LCAccountManager.h"
#import "UserInfo.h"
#import "YYModel.h"
#import "BaiduMobStat.h"
#import "LCNavigationController.h"
#import "LCAppDelegate+LCAVPlay.h"

#import "BaiduMobAdSDK/BaiduMobAdSplash.h"
#import "BaiduMobAdSDK/BaiduMobAdSetting.h"

#import "GDTTrack.h"
#import <Bugly/Bugly.h>



// 引入JPush功能所需头文件
#import "JPUSHService.h"
// iOS10注册APNs所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
// 如果需要使用idfa功能所需要引入的头文件（可选）
#import <AdSupport/AdSupport.h>
#define JPUSHIAPPKey "b948576723d40c6eccb3fd40"
//
@interface LCAppDelegate () <WXApiDelegate,BaiduMobAdSplashDelegate,JPUSHRegisterDelegate,UIAlertViewDelegate>

@property (nonatomic, strong) BaiduMobAdSplash *splash;
@property (nonatomic, retain) UIView *customSplashView;

@end

@implementation LCAppDelegate
//此方法会在设备横竖屏变化的时候调用
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
    if (self.rotateDirection == 1){
        return UIInterfaceOrientationMaskLandscapeRight; // 支持右屏旋转
    }
    return UIInterfaceOrientationMaskPortrait;
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
 
    [self setupUserAgent];
    //初始化Bugly
    [Bugly startWithAppId:@"665bef057e"];
    //百度统计
    [[BaiduMobStat defaultStat] startWithAppId:@"650ef06636"];
//    //微信登录
//    [WXApi registerApp:@"wx3efe3706948d8cb2"];//old wx2e1cd5603d43921d
////wxb036dc754d83df5d  这个是安卓的    wx3efe3706948d8cb2 iOS的
    [self setupShareSDK];
    //初始化播放配置
    [self setupAVAudioConfig];
    [self addJPUSH:launchOptions];//极光
//    //初始化蒲公英上报 Crash SDK
//    [self setupPgySDK];
    return YES;
}
#pragma mark - 极光推送
-(void)addJPUSH:(NSDictionary *)launchOptions
{
    //添加初始化APNs代码
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {

    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    NSString *advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    [JPUSHService setupWithOption:launchOptions appKey:@JPUSHIAPPKey
                          channel:@"App Store"
                 apsForProduction:isProduction
            advertisingIdentifier:advertisingId];
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
        if(resCode == 0){
            NSLog(@"registrationID获取成功：%@",registrationID);
        }
        else{
            NSLog(@"registrationID获取失败，code：%d",resCode);
        }
    }];
    NSDictionary *remoteUserInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    if (remoteUserInfo) {//远程通知启动App
        [self recordTheInformationSentByTheNotification:remoteUserInfo];
    }
}
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    [JPUSHService registerDeviceToken:deviceToken];
    if(![[_UserM usercode] isEqualToString:@""]){
        [JPUSHService setAlias:[_UserM usercode] completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
            if (iResCode == 0) {
//                NSLog(@"添加别名成功");
            }
        } seq:0];
    }
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}
#pragma mark- JPUSHRegisterDelegate
//iOS7及以上系统，收到通知
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler: (void (^)(UIBackgroundFetchResult))completionHandler {
    if (application.applicationState == UIApplicationStateActive) {
        //在应用程序中
        [self recordTheInformationSentByTheNotification:userInfo];
    }else if (application.applicationState ==  UIApplicationStateBackground){
        //屏幕锁着的情况
        [self addAlertController:userInfo];
    }else{
        //      在后台
        [self addAlertController:userInfo];
    }
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}
- (void)application:(UIApplication *)application
didReceiveLocalNotification:(UILocalNotification *)notification {
    [JPUSHService showLocalNotificationAtFront:notification identifierKey:nil];
}
#pragma mark - 在APP内收到通知
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    NSDictionary * userInfo = notification.request.content.userInfo;
    UNNotificationRequest *request = notification.request; // 收到推送的请求
    UNNotificationContent *content = request.content; // 收到推送的消息内容
//    NSNumber *badge = content.badge;  // 推送消息的角标
    NSString *body = content.body;    // 推送消息体
    UNNotificationSound *sound = content.sound;  // 推送消息的声音
    NSString *subtitle = content.subtitle;  // 推送消息的副标题
    NSString *title = content.title;  // 推送消息的标题
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]){
        [JPUSHService handleRemoteNotification:userInfo];
        [self recordTheInformationSentByTheNotification:userInfo];
    }
    else{
        [self recordTheInformationSentByTheNotification:userInfo];
        // 判断为本地通知
        NSLog(@"iOS10 前台收到本地通知:{\nbody:%@，\ntitle:%@,\nsubtitle:%@,\nbadge：%@，\nsound：%@，\nuserInfo：%@\n}",body,title,subtitle,sound,userInfo);
    }
    completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以设置
}
#pragma mark - 在APP外收到的通知
// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler
{
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    UNNotificationRequest *request = response.notification.request; // 收到推送的请求
    UNNotificationContent *content = request.content; // 收到推送的消息内容
    NSNumber *badge = content.badge;  // 推送消息的角标
    NSString *body = content.body;    // 推送消息体
    UNNotificationSound *sound = content.sound;  // 推送消息的声音
    NSString *subtitle = content.subtitle;  // 推送消息的副标题
    NSString *title = content.title;  // 推送消息的标题
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        [self addAlertController:userInfo];
     }
    else{
        // 判断为本地通知
        [self addAlertController:userInfo];
        NSLog(@"iOS10 收到本地通知:{\nbody:%@，\ntitle:%@,\nsubtitle:%@,\nbadge：%@，\nsound：%@，\nuserInfo:%@}",body,title,subtitle,sound,userInfo);
    }
    completionHandler();  // 系统要求执行这个方法
}
#pragma mark- 弹窗
-(void)addAlertController:(NSDictionary *)userInfo
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示!" message:userInfo[@"aps"][@"alert"]  preferredStyle:UIAlertControllerStyleAlert];
    // 确定注销
    UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction *_Nonnull action) {
        NSLog(@"取消");
    }];
    UIAlertAction * okAction = [UIAlertAction actionWithTitle:@"去看看" style:UIAlertActionStyleDefault handler:^(UIAlertAction *_Nonnull action) {
        [self alertViewClickbuttonIndex];
    }];
    [alert addAction:cancelAction];
    [alert addAction:okAction];
    [self.window.rootViewController presentViewController:alert animated:YES completion:nil];
}
#pragma mark - 记录通知传过来的信息
-(void)recordTheInformationSentByTheNotification:(NSDictionary *)userInfo
{
    if([userInfo[@"kind"] integerValue] == 2){
        //通知
        NSInteger A = [[_UserM msg_not_read] integerValue];
        [_UserM setMsg_not_read: [NSString stringWithFormat:@"%ld",(long)A+1]];
    }else{
        NSInteger A = [[_UserM sys_not_read] integerValue];
        [_UserM setSys_not_read: [NSString stringWithFormat:@"%ld",(long)A+1]];
    }
    NSNotification *notification =[NSNotification notificationWithName:@"ANewMessage" object:nil userInfo:nil];
    [[NSNotificationCenter defaultCenter] postNotification:notification];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"ANewMessage" object:nil];
}
#pragma mark - 跳转通知界面
-(void)alertViewClickbuttonIndex
{
    __weak typeof(self) weakSelf = self;
    // 类名
    NSString *class = @"LSZNotifyClassificationVC";
    const char *className = [class cStringUsingEncoding:NSASCIIStringEncoding];
    // 从一个字串返回一个类
    Class newClass = objc_getClass(className);
    if (!newClass){
        // 创建一个类
        Class superClass = [NSObject class];
        newClass = objc_allocateClassPair(superClass, className, 0);
        // 注册你创建的这个类
        objc_registerClassPair(newClass);
    }
    // 创建对象
    id instance = [[newClass alloc] init];
    if ([instance isKindOfClass:[LSZNotifyClassificationVC class]]) {
        UITabBarController *tabVC = (UITabBarController *)weakSelf.window.rootViewController;
        UINavigationController *pushClassStance = (UINavigationController *)tabVC.viewControllers[tabVC.selectedIndex];
        // 跳转到对应的控制器
        [pushClassStance pushViewController:instance animated:YES];
    }else{
        UITabBarController *tabVC = (UITabBarController *)weakSelf.window.rootViewController;
        UINavigationController *pushClassStance = (UINavigationController *)tabVC.viewControllers[tabVC.selectedIndex];
        // 跳转到对应的控制器
        [pushClassStance pushViewController:instance animated:YES];
    }
}
- (NSString *)logDic:(NSDictionary *)dic {
    if (![dic count]) {
        return nil;
    }
    NSString *tempStr1 =
    [[dic description] stringByReplacingOccurrencesOfString:@"\\u"
                                                 withString:@"\\U"];
    NSString *tempStr2 =
    [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
    NSString *tempStr3 =
    [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
    NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
    NSString *str =
    [NSPropertyListSerialization propertyListFromData:tempData
                                     mutabilityOption:NSPropertyListImmutable
                                               format:NULL
                                     errorDescription:NULL];
    return str;
}
/////设置蒲公英SDK
//-(void)setupPgySDK{
//    //启动基本SDK
//    [[PgyManager sharedPgyManager] startManagerWithAppId:@"a913041ea7dde6e4af48fe72c1ed0f38"];
////  默认开启,所以设置为NO,关闭用户反馈
//    [[PgyManager sharedPgyManager] setEnableFeedback:NO];
////    // 设置用户反馈界面激活方式为三指拖动
////    [[PgyManager sharedPgyManager] setFeedbackActiveType:kPGYFeedbackActiveTypeThreeFingersPan];
////
////    // 设置用户反馈界面激活方式为摇一摇
////    [[PgyManager sharedPgyManager] setFeedbackActiveType:kPGYFeedbackActiveTypeShake];
//}

///设置ShareSDK
- (void)setupShareSDK {
    
    [ShareSDK registerActivePlatforms:@[
//                                        @(SSDKPlatformTypeWechat),
                                        @(SSDKPlatformSubTypeWechatSession),
                                        @(SSDKPlatformSubTypeWechatTimeline),
                                        @(SSDKPlatformTypeQQ),
                                        @(SSDKPlatformTypeSinaWeibo)
                                        ]
     
                             onImport:^(SSDKPlatformType platformType)
     {
         switch (platformType)
         {
             case SSDKPlatformTypeWechat:
                 [ShareSDKConnector connectWeChat:[WXApi class]];
                 break;
             case SSDKPlatformTypeQQ:
                 [ShareSDKConnector connectQQ:[QQApiInterface class] tencentOAuthClass:[TencentOAuth class]];
                 break;
             case SSDKPlatformTypeSinaWeibo:
                 [ShareSDKConnector connectWeibo:[WeiboSDK class]];
                 break;
             default:
                 break;
         }
     }
                      onConfiguration:^(SSDKPlatformType platformType, NSMutableDictionary *appInfo)
     {
         switch (platformType)
         {
             case SSDKPlatformTypeWechat:
//                 [appInfo SSDKSetupWeChatByAppId:@"wx3efe3706948d8cb2"
//                                       appSecret:@"5f691be10d09e41c30ad72bf63fc2f8a"];
                 [appInfo SSDKSetupWeChatByAppId:@"wxb036dc754d83df5d"
                                       appSecret:@"2ea46c484f05a72f7a4a56f59491d95d"];//a69ef590b98c7c973107f198630bf335"];
                 break;
             
             case SSDKPlatformTypeSinaWeibo:
                 //设置新浪微博应用信息,其中authType设置为使用SSO＋Web形式授权
                 [appInfo SSDKSetupSinaWeiboByAppKey:@"803453789"
                                           appSecret:@"0041b893153e88600ec6c989eb88e517"
                                         redirectUri:@"http://www.9ku.com/fuyin/shengjing.htm"
                                            authType:SSDKAuthTypeBoth];
                 break;

             
             case SSDKPlatformTypeQQ:
                 [appInfo SSDKSetupQQByAppId:@"1106966342"
                                      appKey:@"aEyEDifpRbOV2Ny5"
                                    authType:SSDKAuthTypeBoth];
                 break;

             default:
                 break;
         }
     }];
    
    [OpenShare connectWeixinWithAppId:@"wxb036dc754d83df5d"];
    [OpenShare connectQQWithAppId:@"1106966342"];
    [OpenShare connectWeiboWithAppKey:@"803453789"];

}

///设置浏览器 代理标识
- (void)setupUserAgent {
    UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectZero];
    NSString *userAgent = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
    NSString *newUserAgent = [userAgent stringByAppendingString:@" CK 2.0"];//自定义需要拼接的字符串
    NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:newUserAgent, @"UserAgent", nil];
    [[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
}

#pragma mark - 配置引导页和主页
-(void)setupApplication:(NSString *)clzName ControllerType:(NSInteger)controllerType{
    Class clz = NSClassFromString(clzName);//将字符串转化成class
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];//windows底色为白色
    if (controllerType == 1) {
        UITabBarController *controller = [[clz alloc] init];
        //引导页判断
        //    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Guide" bundle:nil];
        //    UIViewController *controller = [sb instantiateInitialViewController];
        //    self.window.rootViewController = [self selectRootStr] ? controller :tabBarController;
          //无引导页
        self.window.rootViewController = controller;
    }
    else if (controllerType == 0){
        UIViewController *viewController = [[clz alloc] init];
//        controller.title = title;
        
        //引导页判断
        //    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Guide" bundle:nil];
        //    UIViewController *controller = [sb instantiateInitialViewController];
//         self.window.rootViewController = [self selectRootStr] ? controller :viewController;
        
        //无引导页
        LCNavigationController *navController = [[LCNavigationController alloc] initWithRootViewController:viewController];

        self.window.rootViewController = navController;
    }

    [self.window makeKeyAndVisible];
    //baidu广告
//    [self loadBaiduMob];
    //广点通
    //    [self guangDiantong];

}

#pragma mark - 首启动根控制器选择
- (Boolean)selectRootStr
{
    //根据版本号判断是否首次启动,选择启动控制器
    NSUserDefaults* defaulut = [NSUserDefaults standardUserDefaults];
    
    // 从沙盒中读取上一次存储的手机版本号
    NSString* lastVersion = [defaulut objectForKey:@"appVersion"];
    
//    UIViewController * mainController;
    // 获取当前的手机应用版本号
    NSDictionary* dict = [NSBundle mainBundle].infoDictionary;
    NSString* appVersion = dict[@"CFBundleShortVersionString"];
    [defaulut setObject:appVersion forKey:@"appVersion"];//存储手机应用版本
    [defaulut synchronize];
    
    //判断版本号,选择控制器
    if (![lastVersion isEqualToString:appVersion]) {
        NSLog(@"第一次启动");
        return true;
    }

    return false;

}
// 实现和微信终端交互的具体请求与回应，因此需要实现WXApiDelegate协议的两个方法：
- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation
{
    if ([OpenShare handleOpenURL:url]) {
        return YES;
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        [WXApi handleOpenURL:url delegate:self];
    });
    return YES;
}

- (BOOL)application:(UIApplication *)app
            openURL:(NSURL *)url
            options:(NSDictionary<NSString *,id> *)options
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [WXApi handleOpenURL:url delegate:self];
    });
    return YES;
}

-(void)onReq:(SendAuthReq *)req{
    NSLog(@"req = %@", req);
}
-(void)onResp:(SendAuthResp *)resp{
    [SVProgressHUD dismiss];
    
    NSLog(@"errCode = %d", resp.errCode);
    if (resp.errCode == 0) {
//        NSLog(@"code = %@", resp.code);
//        NSLog(@"state = %@", resp.state);
//        NSLog(@"state = %@", resp.lang);
//        NSLog(@"state = %@", resp.country);
        
//        NSDictionary *parameters = @{@"wx_code":resp.code};
                                     //,@"mobile":@"17621218581" ,@"code":@(937340)};
        
//        [kNetworkTool POSTFuYinWithUrlString:WX_LOGIN_URL input:parameters success:^(NSDictionary *responseObject) {
//            NSLog(@"responseObject = %@", responseObject);
//        } failure:^(NSError *error) {   NSLog(@"error = %@", error);
//        }];
    }
    
    
}

///baidu广告
-(void)loadBaiduMob{
    BaiduMobAdSplash *splash = [[BaiduMobAdSplash alloc] init];
    splash.delegate = self;
    splash.AdUnitTag = @"4927344";
    splash.canSplashClick = YES;
    self.splash = splash;
    
    //可以在customSplashView上显示包含icon的自定义开屏
    self.customSplashView = [[UIView alloc]initWithFrame:self.window.frame];
    self.customSplashView.backgroundColor = [UIColor whiteColor];
    [self.window addSubview:self.customSplashView];
    
    CGFloat screenWidth = self.window.frame.size.width;
    CGFloat screenHeight = self.window.frame.size.height;
    
    //在baiduSplashContainer用做上展现百度广告的容器，注意尺寸必须大于200*200，并且baiduSplashContainer需要全部在window内，同时开机画面不建议旋转
    UIView * baiduSplashContainer = [[UIView alloc]initWithFrame:CGRectMake(0, 0, screenWidth, screenHeight - 100)];
    [self.customSplashView addSubview:baiduSplashContainer];
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, screenHeight - 100, screenWidth, 100)];
    imageView.image = [UIImage imageNamed:@"gdt_splash_logo"];
    [self.customSplashView addSubview:imageView];
    
    //
    //在的baiduSplashContainer里展现百度广告
    [splash loadAndDisplayUsingContainerView:baiduSplashContainer];
    
}
- (NSString *)publisherId {
    return @"b3a6d662";
}

- (void)splashDidClicked:(BaiduMobAdSplash *)splash {
    NSLog(@"splashDidClicked");//点击广告之后会触发
}

- (void)splashDidDismissLp:(BaiduMobAdSplash *)splash {
    NSLog(@"splashDidDismissLp");
}

- (void)splashDidDismissScreen:(BaiduMobAdSplash *)splash {
    NSLog(@"splashDidDismissScreen");
    [self removeSplash];
}

- (void)splashSuccessPresentScreen:(BaiduMobAdSplash *)splash {
    NSLog(@"splashSuccessPresentScreen");
}

- (void)splashlFailPresentScreen:(BaiduMobAdSplash *)splash withError:(BaiduMobFailReason)reason {
    NSLog(@"splashlFailPresentScreen withError %d", reason);
    [self removeSplash];
}

/**
 *  展示结束or展示失败后, 手动移除splash和delegate
 */
- (void) removeSplash {
    if (self.splash) {
        self.splash.delegate = nil;
        self.splash = nil;
        [self.customSplashView removeFromSuperview];
    }
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    [GDTTrack activateApp];
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    [JPUSHService setBadge:0];//去除极光推送的角标

    [LSZRequestData getsStatisticsForMessagesNotRead:^(BOOL isOK, NSString * STRING, NSDictionary * dic) {
        if (isOK == YES) {
            if([NSStr([_UserM sys_not_read]) isEqualToString:NSStr(dic[@"data"][@"sys_not_read"])]&&[NSStr([_UserM msg_not_read]) isEqualToString:NSStr(dic[@"data"][@"msg_not_read"])]){

            }else{
                [_UserM setSys_not_read:dic[@"data"][@"sys_not_read"]];
                [_UserM setMsg_not_read:dic[@"data"][@"msg_not_read"]];
                NSNotification *notification =[NSNotification notificationWithName:@"ANewMessage" object:nil userInfo:nil];
                [[NSNotificationCenter defaultCenter] postNotification:notification];
                [[NSNotificationCenter defaultCenter] removeObserver:self name:@"ANewMessage" object:nil];
            }
        }
    }];
}
- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"ANewMessage" object:nil];
}

@end
